const WebSocket = require('ws');

const CONFIG = {
    serverUrl: 'ws://localhost:3001/user-service/websocket',
    testUser: {
        mobile: '13800138000',
        password: '123456'
    }
};

class Code1475Tester {
    constructor() {
        this.token = null;
        this.ws = null;
        this.characters = [];
        this.testResults = [];
    }

    addTestResult(testName, success, message) {
        this.testResults.push({ testName, success, message });
        console.log(`${success ? '✅' : '❌'} ${testName}: ${message}`);
    }

    async delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    async testLogin() {
        console.log('🔐 步骤1: 用户登录...');

        try {
            const response = await fetch('http://localhost:3001/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    mobile: CONFIG.testUser.mobile,
                    password: CONFIG.testUser.password,
                }),
            });

            const data = await response.json();

            if (data.code === 0 && data.data?.token) {
                this.token = data.data.token;
                console.log('✅ 登录成功，获取到token');
                this.addTestResult('用户登录', true, '登录成功');
                return true;
            } else {
                console.log('❌ 登录失败:', data.message);
                this.addTestResult('用户登录', false, data.message || '登录失败');
                return false;
            }
        } catch (error) {
            console.error('❌ 登录请求失败:', error.message);
            this.addTestResult('用户登录', false, `请求失败: ${error.message}`);
            return false;
        }
    }

    async testWebSocketConnection() {
        console.log('\n🔌 步骤2: 建立WebSocket连接...');

        return new Promise((resolve, reject) => {
            this.ws = new WebSocket(CONFIG.serverUrl);

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接已建立');
                this.addTestResult('WebSocket连接', true, '连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接错误:', error.message);
                this.addTestResult('WebSocket连接', false, `连接错误: ${error.message}`);
                reject(error);
            });

            this.ws.on('close', () => {
                console.log('🔌 WebSocket连接已关闭');
            });

            // 设置连接超时
            setTimeout(() => {
                if (this.ws.readyState !== WebSocket.OPEN) {
                    reject(new Error('WebSocket连接超时'));
                }
            }, 10000);
        });
    }

    async testAuthentication() {
        console.log('\n🔑 步骤3: WebSocket身份验证...');

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('WebSocket身份验证', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 发送认证消息
            const authMessage = {
                c: 1,
                d: {
                    token: this.token
                }
            };

            this.ws.send(JSON.stringify(authMessage));

            // 等待认证响应
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            console.log('✅ WebSocket身份验证成功');
                            this.addTestResult('WebSocket身份验证', true, '验证成功');
                        } else {
                            console.log('❌ WebSocket身份验证失败:', message.message);
                            this.addTestResult('WebSocket身份验证', false, message.message || '验证失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('WebSocket身份验证', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('WebSocket身份验证', false, '等待响应超时');
                resolve();
            }, 10000);
        });
    }

    async testQueryCharacters() {
        console.log('\n📋 步骤4: 查询角色列表...');

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('查询角色列表', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            this.characters = message.roleList;
                            console.log(`✅ 查询成功，共${message.roleCount || message.roleList.length}个角色`);
                            this.addTestResult('查询角色列表', true, `获取${this.characters.length}个角色`);
                        } else {
                            this.characters = [];
                            console.log('✅ 查询成功，暂无角色');
                            this.addTestResult('查询角色列表', true, '获取0个角色');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('查询角色列表', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送查询角色列表请求
            this.ws.send(JSON.stringify({
                c: 3,
                d: null
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('查询角色列表', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testSoftDeleteCharacter() {
        console.log('\n🗑️ 步骤5: 测试软删除角色...');

        if (this.characters.length === 0) {
            console.log('⚠️ 没有角色可删除，跳过测试');
            this.addTestResult('软删除角色', true, '跳过测试（无角色）');
            return;
        }

        // 选择一个等级不超过30级的角色进行删除测试
        const targetCharacter = this.characters.find(char => char.lvl <= 30);

        if (!targetCharacter) {
            console.log('⚠️ 没有等级不超过30级的角色可删除，跳过测试');
            this.addTestResult('软删除角色', true, '跳过测试（无符合条件的角色）');
            return;
        }

        console.log(`🎯 选择角色进行删除测试: ${targetCharacter.name} (ID: ${targetCharacter.id}, 等级: ${targetCharacter.lvl})`);

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('软删除角色', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 1475) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.code === 0) {
                            console.log('✅ 角色软删除成功');
                            this.addTestResult('软删除角色', true, message.message || '删除成功');
                        } else {
                            console.log('❌ 角色软删除失败:', message.message);
                            this.addTestResult('软删除角色', false, message.message || '删除失败');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('软删除角色', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 发送软删除角色请求
            this.ws.send(JSON.stringify({
                c: 1475,
                d: {
                    roleid: targetCharacter.id
                }
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('软删除角色', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async testVerifyCharacterDeleted() {
        console.log('\n🔍 步骤6: 验证角色已被删除...');

        return new Promise((resolve) => {
            if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
                this.addTestResult('验证角色删除', false, 'WebSocket未连接');
                resolve();
                return;
            }

            // 设置响应监听器
            const responseHandler = (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    if (message.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);

                        if (message.roleList && Array.isArray(message.roleList)) {
                            const newCharacterCount = message.roleList.length;
                            const originalCharacterCount = this.characters.length;

                            if (newCharacterCount < originalCharacterCount) {
                                console.log(`✅ 验证成功：角色数量从${originalCharacterCount}减少到${newCharacterCount}`);
                                this.addTestResult('验证角色删除', true, `角色数量减少: ${originalCharacterCount} -> ${newCharacterCount}`);
                            } else {
                                console.log('⚠️ 角色数量未减少，可能删除失败');
                                this.addTestResult('验证角色删除', false, '角色数量未减少');
                            }
                        } else {
                            console.log('✅ 验证成功：角色列表为空');
                            this.addTestResult('验证角色删除', true, '角色列表为空');
                        }
                        resolve();
                    }
                } catch (error) {
                    this.ws.removeListener('message', responseHandler);
                    this.addTestResult('验证角色删除', false, '响应解析失败');
                    resolve();
                }
            };

            this.ws.on('message', responseHandler);

            // 重新查询角色列表
            this.ws.send(JSON.stringify({
                c: 3,
                d: null
            }));

            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                this.addTestResult('验证角色删除', false, '请求超时');
                resolve();
            }, 10000);
        });
    }

    async runAllTests() {
        console.log('🧪 开始测试1475软删除角色指令功能...\n');

        try {
            // 1. 用户登录
            if (!(await this.testLogin())) {
                console.log('❌ 登录失败，无法继续测试');
                return;
            }

            // 2. 建立WebSocket连接
            await this.testWebSocketConnection();

            // 3. WebSocket身份验证
            await this.testAuthentication();

            // 4. 查询角色列表
            await this.testQueryCharacters();

            // 5. 测试软删除角色
            await this.testSoftDeleteCharacter();

            // 6. 验证角色已被删除
            await this.testVerifyCharacterDeleted();

            // 输出测试结果汇总
            console.log('\n📊 测试结果汇总:');
            this.testResults.forEach(result => {
                console.log(`${result.success ? '✅' : '❌'} ${result.testName}: ${result.message}`);
            });

            const successCount = this.testResults.filter(r => r.success).length;
            const totalCount = this.testResults.length;
            console.log(`\n🎯 测试完成: ${successCount}/${totalCount} 项测试通过`);

        } catch (error) {
            console.error('❌ 测试过程中发生错误:', error.message);
        } finally {
            // 关闭WebSocket连接
            if (this.ws) {
                this.ws.close();
            }
        }
    }
}

// 运行测试
const tester = new Code1475Tester();
tester.runAllTests();
